const pool = require('../config/db');

/**
 * @desc    获取所有班级
 * @route   GET /api/classes
 * @access  Private/Admin
 */
const getClasses = async (req, res) => {
    try {
    const [classes] = await pool.query(`
        SELECT c.*, t.name as head_teacher_name, t.teacher_id as head_teacher_id
        FROM classes c
        LEFT JOIN teachers t ON c.head_teacher_id = t.id
        ORDER BY c.name
    `);
    
    // 获取每个班级的学生数量
    const classesWithStudentCount = await Promise.all(
        classes.map(async (cls) => {
        const [studentCount] = await pool.query(
            'SELECT COUNT(*) as count FROM students WHERE class_id = ?',
            [cls.id]
        );
        
        return {
            ...cls,
            student_count: studentCount[0].count
        };
        })
    );
    
    res.json(classesWithStudentCount);
    } catch (error) {
    console.error('获取班级列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    获取单个班级
 * @route   GET /api/classes/:id
 * @access  Private/Admin
 */
const getClassById = async (req, res) => {
    try {
    const [classes] = await pool.query(`
        SELECT c.*, t.name as head_teacher_name, t.teacher_id as head_teacher_id
        FROM classes c
        LEFT JOIN teachers t ON c.head_teacher_id = t.id
        WHERE c.id = ?
    `, [req.params.id]);

    if (classes.length === 0) {
        return res.status(404).json({ message: '班级不存在' });
    }

    const cls = classes[0];
    
    // 获取班级学生数量
    const [studentCount] = await pool.query(
        'SELECT COUNT(*) as count FROM students WHERE class_id = ?',
        [cls.id]
    );
    
    // 获取班级学生列表
    const [students] = await pool.query(
        'SELECT * FROM students WHERE class_id = ? ORDER BY student_id',
        [cls.id]
    );
    
    res.json({
        ...cls,
        student_count: studentCount[0].count,
        students
    });
    } catch (error) {
    console.error('获取班级信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    创建班级
 * @route   POST /api/classes
 * @access  Private/Admin
 */
const createClass = async (req, res) => {
    try {
    const { name, head_teacher_id } = req.body;

    // 验证班级名称
    if (!name) {
        return res.status(400).json({ message: '班级名称为必填项' });
    }

    // 检查班级名称是否已存在
    const [existingClasses] = await pool.query(
        'SELECT * FROM classes WHERE name = ?',
        [name]
    );

    if (existingClasses.length > 0) {
        return res.status(400).json({ message: '该班级名称已存在' });
    }

    // 检查班主任是否存在且是班主任角色
    if (head_teacher_id) {
        const [teachers] = await pool.query(
        'SELECT * FROM teachers WHERE id = ? AND is_head_teacher = true',
        [head_teacher_id]
        );

        if (teachers.length === 0) {
        return res.status(400).json({ message: '指定的班主任不存在或不是班主任' });
        }
    }

    // 创建班级
    const [result] = await pool.query(
        'INSERT INTO classes (name, head_teacher_id) VALUES (?, ?)',
        [name, head_teacher_id || null]
    );

    // 获取创建的班级
    const [newClasses] = await pool.query(`
        SELECT c.*, t.name as head_teacher_name, t.teacher_id as head_teacher_id
        FROM classes c
        LEFT JOIN teachers t ON c.head_teacher_id = t.id
        WHERE c.id = ?
    `, [result.insertId]);

    res.status(201).json({
        message: '班级创建成功',
        class: newClasses[0]
    });
    } catch (error) {
    console.error('创建班级错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    更新班级
 * @route   PUT /api/classes/:id
 * @access  Private/Admin
 */
const updateClass = async (req, res) => {
    try {
    const { name, head_teacher_id } = req.body;

    // 检查班级是否存在
    const [classes] = await pool.query(
        'SELECT * FROM classes WHERE id = ?',
        [req.params.id]
    );

    if (classes.length === 0) {
        return res.status(404).json({ message: '班级不存在' });
    }

    // 验证班级名称
    if (!name) {
        return res.status(400).json({ message: '班级名称为必填项' });
    }

    // 检查班级名称是否已被其他班级使用
    if (name !== classes[0].name) {
        const [existingClasses] = await pool.query(
        'SELECT * FROM classes WHERE name = ? AND id != ?',
        [name, req.params.id]
        );

        if (existingClasses.length > 0) {
        return res.status(400).json({ message: '该班级名称已存在' });
        }
    }

    // 检查班主任是否存在且是班主任角色
    if (head_teacher_id) {
        const [teachers] = await pool.query(
        'SELECT * FROM teachers WHERE id = ? AND is_head_teacher = true',
        [head_teacher_id]
        );

        if (teachers.length === 0) {
        return res.status(400).json({ message: '指定的班主任不存在或不是班主任' });
        }
    }

    // 更新班级
    await pool.query(
        'UPDATE classes SET name = ?, head_teacher_id = ? WHERE id = ?',
        [name, head_teacher_id || null, req.params.id]
    );

    // 获取更新后的班级
    const [updatedClasses] = await pool.query(`
        SELECT c.*, t.name as head_teacher_name, t.teacher_id as head_teacher_id
        FROM classes c
        LEFT JOIN teachers t ON c.head_teacher_id = t.id
        WHERE c.id = ?
    `, [req.params.id]);

    res.json({
        message: '班级更新成功',
        class: updatedClasses[0]
    });
    } catch (error) {
    console.error('更新班级错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    删除班级
 * @route   DELETE /api/classes/:id
 * @access  Private/Admin
 */
const deleteClass = async (req, res) => {
    try {
    // 检查班级是否存在
    const [classes] = await pool.query(
        'SELECT * FROM classes WHERE id = ?',
        [req.params.id]
    );

    if (classes.length === 0) {
        return res.status(404).json({ message: '班级不存在' });
    }

    // 将该班级的学生的class_id设为null
    await pool.query(
        'UPDATE students SET class_id = NULL WHERE class_id = ?',
        [req.params.id]
    );

    // 删除班级
    await pool.query(
        'DELETE FROM classes WHERE id = ?',
        [req.params.id]
    );

    res.json({ message: '班级删除成功' });
    } catch (error) {
    console.error('删除班级错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    根据token获取当前班级总人数和班主任信息
 * @route   GET /api/classes/current-info
 * @access  Private
 */
const getCurrentClassInfo = async (req, res) => {
    try {
    // 这里假设用户与班级有某种关联，实际应用中可能需要调整
    // 为了演示，我们返回所有班级的信息
    const [classes] = await pool.query(`
        SELECT 
        c.id, 
        c.name, 
        t.name as head_teacher_name,
        t.teacher_id as head_teacher_id,
        COUNT(s.id) as student_count
        FROM classes c
        LEFT JOIN teachers t ON c.head_teacher_id = t.id
        LEFT JOIN students s ON c.id = s.class_id
        GROUP BY c.id, c.name, t.name, t.teacher_id
    `);
    
    res.json(classes);
    } catch (error) {
    console.error('获取班级信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    getClasses,
    getClassById,
    createClass,
    updateClass,
    deleteClass,
    getCurrentClassInfo
};
